package com.ttc.group2.videochat.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.quickblox.auth.QBAuth;
import com.quickblox.auth.model.QBSession;
import com.quickblox.chat.QBChatService;
import com.quickblox.core.QBEntityCallbackImpl;
import com.quickblox.users.QBUsers;
import com.quickblox.users.model.QBUser;
import com.ttc.group2.videochat.R;
import com.ttc.group2.videochat.VideoChatApplication;
import com.ttc.group2.videochat.database.DbHelper;
import com.ttc.group2.videochat.model.User;
import com.ttc.group2.videochat.utils.DialogUtils;
import com.ttc.group2.videochat.utils.NetworkUtils;
import com.ttc.group2.videochat.utils.UserUtils;

public class LoginActivity extends Activity implements OnClickListener {
	private ProgressDialog progressDialog;
	private EditText loginEditText;
	private EditText passwordEditText;
	private Button btnLogin;
	private Button btnSignUp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		// init ChatService
		initChatService();

		// init UI
		initView();

		setListener();

		if (!NetworkUtils.isNetworkAvailable(this)) {
			DialogUtils.showToast(this,
					getString(R.string.no_internet_available),
					Toast.LENGTH_LONG);
		} else {
			// check session exists

		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private void initView() {
		loginEditText = (EditText) findViewById(R.id.login_username);
		passwordEditText = (EditText) findViewById(R.id.login_password);

		btnLogin = (Button) findViewById(R.id.main_btnSignIn);
		btnSignUp = (Button) findViewById(R.id.main_btnSignUp);

	}

	private void setListener() {
		btnLogin.setOnClickListener(this);
		btnSignUp.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.main_btnSignIn:
			if (!NetworkUtils.isNetworkAvailable(this)) {
				DialogUtils.showToast(this,
						getString(R.string.no_internet_available),
						Toast.LENGTH_SHORT);
			} else {
				requestLogin();
			}
			break;

		case R.id.main_btnSignUp:
			//
			showSignUpActivity();
			break;

		default:
			break;
		}
	}

	private void initChatService() {
		if (!QBChatService.isInitialized()) {
			QBChatService.init(this);
		} else {
			Log.d("ActivityLogin", "InitChat not needed");
		}
	}

	private void startMainActivity() {
		startActivity(new Intent(this, MainActivity.class));
		finish();
	}

	private boolean checkInputs() {
		boolean flag = false;
		String login = loginEditText.getText().toString().trim();
		String password = passwordEditText.getText().toString().trim();
		if (!TextUtils.isEmpty(password) && !TextUtils.isEmpty(login)) {
			// loginEditText.requestFocus();
			flag = true;
		} else {
			flag = false;
		}

		return flag;
	}

	// Show SignUp Activity
	private void showSignUpActivity() {

	}

	private boolean requestLogin() {
		// Create session login
		checkLogin();
		return true;
	}

	// Request Login
	private void checkLogin() {
		if (checkInputs()) {
			progressDialog = new ProgressDialog(this);
			progressDialog.setMessage(getString(R.string.please_wait));
			progressDialog.setCancelable(false);
			progressDialog.show();

			// Sign in application with user
			String login = loginEditText.getText().toString().trim();
			String password = passwordEditText.getText().toString().trim();

			// Create session login with user & password
			createSession(login, password);

		} else {
			DialogUtils.showToast(this,
					getString(R.string.incorrect_input_data),
					Toast.LENGTH_SHORT);
		}
	}

	private void createSession(String login, final String password) {
		QBAuth.createSession(login, password,
				new QBEntityCallbackImpl<QBSession>() {
					@Override
					public void onSuccess(QBSession qbSession, Bundle bundle) {
						// Save current user
						VideoChatApplication app = (VideoChatApplication) getApplication();
						app.setCurrentUser(qbSession.getUserId(), password);

						// get list users
						getAllUser();
					}

					@Override
					public void onError(List<String> errors) {
						progressDialog.dismiss();
						Toast.makeText(LoginActivity.this, errors.get(0),
								Toast.LENGTH_SHORT).show();
					}
				});
	}

	private void getAllUser() {
		QBUsers.getUsers(null, new QBEntityCallbackImpl<ArrayList<QBUser>>() {
			@Override
			public void onSuccess(ArrayList<QBUser> qbUsers, Bundle bundle) {
				progressDialog.dismiss();
				// Insert Users to database
				new InsertDatabase(qbUsers).execute();
				startMainActivity();
			}

			@Override
			public void onError(List<String> errors) {
				DialogUtils.showToast(LoginActivity.this, errors.get(0),
						Toast.LENGTH_SHORT);
			}
		});
	}

	private class InsertDatabase extends AsyncTask<Void, Void, Void> {
		private List<QBUser> qbUsers;

		public InsertDatabase(List<QBUser> qbUsers) {
			this.qbUsers = qbUsers;
		}

		@Override
		protected Void doInBackground(Void... params) {
			List<User> users = UserUtils.createUsersList(qbUsers);
			DbHelper.getInstance(LoginActivity.this).saveUsers(users);
			return null;
		}

	}

}
